package com.rick.awarenessdemo

import android.app.*
import android.content.Context
import android.content.Intent
import android.os.IBinder
import com.amap.api.services.core.PoiItem
import com.blankj.utilcode.util.AppUtils

/**
 * 前台保活服务
 */
class ForegroundService : Service() {

    companion object {
        private const val KEY_POI_ITEM = "KEY_POI_ITEM"

        @JvmStatic
        fun start(context: Context, poiItem: PoiItem? = null) {
            val intent = Intent(context, ForegroundService::class.java)
            intent.putExtra(KEY_POI_ITEM, poiItem)
            context.startForegroundService(intent)
        }
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val nm = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val nc = NotificationChannel(
            BuildConfig.APPLICATION_ID,
            AppUtils.getAppName(),
            NotificationManager.IMPORTANCE_HIGH
        )
        nm.createNotificationChannel(nc)
        val poiItem = intent?.getParcelableExtra<PoiItem?>(KEY_POI_ITEM)
        startForeground(
            1,
            Notification
                .Builder(this, BuildConfig.APPLICATION_ID)
                .setSmallIcon(R.drawable.remind_small)
                .setAutoCancel(true)
                .setContentTitle(if (poiItem == null) "请设置目的地" else "目的地：${poiItem.title}")
                .setContentIntent(
                    PendingIntent.getActivity(
                        this,
                        0,
                        Intent(this, MainActivity::class.java),
                        PendingIntent.FLAG_UPDATE_CURRENT
                    )
                )
                .build()
        )
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onDestroy() {
        super.onDestroy()
        stopForeground(true)
    }
}
